package com.aso114.project.mvp.activity.fragment;


import android.app.Dialog;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.SimpleAdapter;
import android.widget.TextView;
import android.widget.Toast;

import com.aso114.project.R;
import com.aso114.project.adapter.ExpoundingAdapter;
import com.aso114.project.adapter.GridAdapter;
import com.aso114.project.base.BaseFragment;
import com.aso114.project.bean.BannerBean;
import com.aso114.project.bean.GridBean;
import com.aso114.project.bean.News;
import com.aso114.project.bean.QuestionBean;
import com.aso114.project.commonview.CustomDatePicker;
import com.aso114.project.commonview.MyGridView;
import com.aso114.project.commonview.MyListView;
import com.aso114.project.exam.ExpositionTestActivity;
import com.aso114.project.exam.QuestionTestActivity;
import com.aso114.project.mvp.LoginSP;
import com.aso114.project.mvp.activity.BannerDetaiActivity;
import com.aso114.project.mvp.activity.LoginActivity;
import com.aso114.project.mvp.activity.MyCollectActivity;
import com.aso114.project.mvp.activity.NeedNoticeDetailActivity;
import com.aso114.project.mvp.activity.PracticeHistoryActivity;
import com.aso114.project.mvp.activity.SatPracticeTestActivity;
import com.aso114.project.mvp.model.CallBack;
import com.aso114.project.mvp.model.CommentModel;
import com.aso114.project.util.Constant;
import com.aso114.project.util.Helper;
import com.aso114.project.util.SpfUtil;
import com.aso114.project.util.Timeutils;
import com.aso114.project.util.ToastUtils;
import com.bigkoo.convenientbanner.ConvenientBanner;
import com.bigkoo.convenientbanner.holder.CBViewHolderCreator;
import com.bigkoo.convenientbanner.holder.Holder;
import com.bigkoo.convenientbanner.listener.OnItemClickListener;
import com.bumptech.glide.Glide;

import org.greenrobot.eventbus.EventBus;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Locale;
import java.util.Map;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import butterknife.Unbinder;


/**
 * 申论
 *
 * @author Administrator
 */
public class ExpoundingFragment extends BaseFragment implements OnItemClickListener {

    Unbinder unbinder;

    @BindView(R.id.convenientBanner)
    ConvenientBanner convenientBanner;
    ExpoundingAdapter adapter;
    List<News.DataBean> mData = null;
    Intent intent;
    @BindView(R.id.exlist)
    MyListView exlist;
    @BindView(R.id.home_day1)
    TextView homeDay1;
    @BindView(R.id.home_day2)
    TextView homeDay2;
    @BindView(R.id.home_day3)
    TextView homeDay3;
    @BindView(R.id.currentDate)
    LinearLayout currentDate;

    //轮播下面的小点（小圆点是本地的，自己导入的图片）
    private int[] indicator = {R.mipmap.ej_sjk_ic, R.mipmap.ej_sjk_ic};

    private List<GridBean> list;
    private GridAdapter adpter;
    @BindView(R.id.gridview)
    MyGridView gridview;
    //    private ArrayList<String> bannerList = new ArrayList<>();
    private List<Map<String, Object>> data_list;
    //定义图标数组
    private int[] imageRes = {
            R.mipmap.home_zt_ic,
            R.mipmap.home_sc_ic,
            R.mipmap.home_lx_ic};

    //定义图标下方的名称数组
    private String[] name = {
            "真题模考",
            "收藏题",
            "练习历史"
    };
    private SimpleAdapter sim_adapter;
    private List<BannerBean> bannerList;
    private CustomDatePicker datePicker;
    private String date;
    private int starYear;

    @Override
    protected int getLayoutResourceId() {

        return R.layout.expoundinglayout;
    }

    @Override
    protected void initView() {
        getData();
        getType();
        initPicker();
        CommentModel.getInstant().getAptiudeTest_banner(Constant.essay,"1", new CallBack() {
            @Override
            public void onSuccess(Object o, boolean isSuccess, String msg) {
                Helper.gotoLogin(isSuccess);//token失效去重新登陆
                bannerList = (List<BannerBean>) o;
                System.out.println("banner数组大小===" + bannerList.size());

                initBanner();

            }

            @Override
            public void onFailure(String fail) {
                bannerList = new ArrayList<>();
                BannerBean bn = new BannerBean();

                bn.setLitpic("https://timgsa.baidu.com/timg?image&quality=80&size=b9999_10000&sec=1543408736304&di=a4bfe0ca275ca305834a525c18cd231d&imgtype=0&src=http%3A%2F%2F5b0988e595225.cdn.sohucs.com%2Fimages%2F20181120%2F9c4edc6604e84eba863c75f2e6cd7221.jpeg");
                bannerList.add(bn);
                BannerBean bn1 = new BannerBean();
                bn1.setLitpic("https://timgsa.baidu.com/timg?image&quality=80&size=b9999_10000&sec=1543408563496&di=cbef8feab19013ac5f3b9507a62f75f7&imgtype=0&src=http%3A%2F%2Fd.ifengimg.com%2Fw600%2Fp0.ifengimg.com%2Fpmop%2F2018%2F1105%2F061500E3A7CFE1AA91524E97BEFE84D6A09FE7B7_size98_w1000_h562.jpeg");
                bannerList.add(bn1);

                System.out.println("banner数组大小===" + bannerList.size());
                initBanner();
            }
        });

        //九宫格

        int length = imageRes.length;

        //生成动态数组，并且转入数据
        ArrayList<HashMap<String, Object>> lstImageItem = new ArrayList<HashMap<String, Object>>();
        for (int i = 0; i < length; i++) {
            HashMap<String, Object> map = new HashMap<String, Object>();
            map.put("ItemImage", imageRes[i]);//添加图像资源的ID
            map.put("ItemText", name[i]);//按序号做ItemText
            lstImageItem.add(map);
        }

    }


    private void getType() {
        String[] from = {"image", "text"};
        int[] to = {R.id.iv_icon, R.id.tv_name};
        sim_adapter = new SimpleAdapter(getActivity(), data_list, R.layout.needkownitem, from, to);
        //配置适配器
        gridview.setAdapter(sim_adapter);

        //添加消息处理
        gridview.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
//                Toast.makeText(getActivity(), name[position], Toast.LENGTH_LONG).show();

                if (position == 0) {
                    if (TextUtils.isEmpty(LoginSP.getInstance().getToken())) {
                        ToastUtils.showToast(getActivity(),"您还未登陆,请先登陆");
                        intent = new Intent(getContext(), LoginActivity.class);
                        startActivity(intent);
                        return;
                    }
                    Constant.title_tv = "9";
                    //真题模考
                    intent = new Intent(getContext(), SatPracticeTestActivity.class);
                    intent.putExtra("type", "1");
                    intent.putExtra("catid", Constant.essay);
                    startActivity(intent);
                }
                if (position == 1) {
                    if (TextUtils.isEmpty(LoginSP.getInstance().getToken())) {
                        ToastUtils.showToast(getActivity(),"您还未登陆,请先登陆");
                        intent = new Intent(getContext(), LoginActivity.class);
                        startActivity(intent);
                        return;
                    }
                    Constant.title_tv = "10";
                    //我的收藏
                    intent = new Intent(getContext(), MyCollectActivity.class);
                    intent.putExtra("isLeft",false);
                    startActivity(intent);
                }
                if (position == 2) {
                    if (TextUtils.isEmpty(LoginSP.getInstance().getToken())) {
                        ToastUtils.showToast(getActivity(),"您还未登陆,请先登陆");
                        intent = new Intent(getContext(), LoginActivity.class);
                        startActivity(intent);
                        return;
                    }
                    Constant.title_tv = "11";
                    //练习历史
                    intent = new Intent(getContext(), PracticeHistoryActivity.class);
                    intent.putExtra("catid", Constant.essay);
                    startActivity(intent);
                }

            }
        });
    }


    public List<Map<String, Object>> getData() {
        data_list = new ArrayList<Map<String, Object>>();
        //cion和iconName的长度是相同的，这里任选其一都可以
        for (int i = 0; i < imageRes.length; i++) {
            Map<String, Object> map = new HashMap<String, Object>();
            map.put("image", imageRes[i]);
            map.put("text", name[i]);
            data_list.add(map);
        }

        return data_list;
    }


    private void initBanner() {
        convenientBanner.setPages(new CBViewHolderCreator<NetworkImageHolderView>() {
            @Override
            public NetworkImageHolderView createHolder() {
                return new NetworkImageHolderView();
            }
        }, bannerList);
        convenientBanner.setPointViewVisible(true)//设置指示器是否可见
                //设置自动切换（同时设置了切换时间间隔）
                .startTurning(3000)
                //设置两个点图片作为翻页指示器，不设置则没有指示器，可以根据自己需求自行配合自己的指示器,不需要圆点指示器可用不设
                .setPageIndicator(new int[]{R.mipmap.ej_sjkbai_ic, R.mipmap.ej_sjk_ic})
                //设置指示器的方向（左、中、右）
                .setPageIndicatorAlign(ConvenientBanner.PageIndicatorAlign.CENTER_HORIZONTAL)
                //设置点击监听事件
                .setOnItemClickListener(this)
                //设置手动影响（设置了该项无法手动切换）
                .setManualPageable(true);
        if (bannerList.size() > 1) {
            convenientBanner.setCanLoop(true);
            convenientBanner.setPointViewVisible(true);
        } else {
            convenientBanner.setCanLoop(false);
            convenientBanner.setPointViewVisible(false);
        }
    }

    @OnClick(R.id.currentDate)
    public void onViewClicked() {
        // 日期格式为yyyy-MM-dd
        datePicker.show(date);
    }

    private void initPicker() {
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd", Locale.CHINA);
        date = sdf.format(new Date());
        starYear = Integer.valueOf(date.split("-")[0]);
        //设置当前显示的日期
//        currentDate.setText(date);

        String endTime = SpfUtil.getInstance().getString("dayTime", "2018-01-01");
        dayNum(endTime);

        /**
         * 设置年月日
         */
        /**
         * 设置年月日
         */
        datePicker = new CustomDatePicker(getActivity(), "考试时间", new CustomDatePicker
                .ResultHandler() {
            @Override
            public void handle(String time) throws ParseException {
                dayNum(time.split(" ")[0]);
                SpfUtil.getInstance().putString("dayTime", time.split(" ")[0]);
            }

        }, starYear + "-01-01 00:00", (starYear + 2) + "-12-31 23:59");
        datePicker.showSpecificTime(false); //显示时和分
        datePicker.setIsLoop(true);


    }

    private void dayNum(String time) {
        long starTime = Timeutils.getStringToDate(date, "yyyy-MM-dd");
        long endTime = Timeutils.getStringToDate(time, "yyyy-MM-dd");
        long dayTime = endTime - starTime;
        long day = dayTime / (24 * 60 * 60 * 1000);
        if (day < 0) {
            day = 0;
        }
        String daystr = String.format("%03d", day);
        homeDay1.setText(daystr.substring(0, 1));
        homeDay2.setText(daystr.substring(1, 2));
        homeDay3.setText(daystr.substring(2));
    }

    public class NetworkImageHolderView implements Holder<BannerBean> {
        private ImageView imageView;

        @Override
        public View createView(Context context) {
            imageView = new ImageView(context);
            imageView.setScaleType(ImageView.ScaleType.CENTER_CROP);
            return imageView;
        }

        @Override
        public void UpdateUI(Context context, int position, BannerBean data) {
            Glide.with(getActivity()).load(data.getLitpic()).into(imageView);
        }
    }

    /**
     * banner item点击事件
     */
    @Override
    public void onItemClick(int position) {
        // 获取banner  type
        int type = Integer.valueOf(bannerList.get(position).getLinktype());

        switch (type) {
            case 0:// 无跳转
                break;
            case 1:// 链接
                intent = new Intent(getActivity(), BannerDetaiActivity.class);
                intent.putExtra("linkUrl",bannerList.get(position).getLinkurl());
                startActivity(intent);
                break;
            case 2:// 题库
                final String[] id = bannerList.get(position).getLinkurl().split(",");//[考题ID，行测或申论ID，考区ID]
                View dialogview = getActivity().getLayoutInflater().inflate(
                        R.layout.loading_view, null);
                final Dialog dialog = new Dialog(getActivity(), R.style.dialogStyle);
                dialog.setContentView(dialogview, new ViewGroup.LayoutParams(
                        ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT));
                dialog.getWindow().setGravity(Gravity.CENTER);
                // 设置点击外围解散
                dialog.setCanceledOnTouchOutside(true);
                dialog.setCancelable(true);//设置是否可以按退回键取消
                dialog.show();
                Constant.title_tv = "3";
                CommentModel.getInstant().get_question_bank(id[2], id[0], id[1], new CallBack() {
                    @Override
                    public void onSuccess(Object o, boolean isSuccess, String msg) {
                        dialog.cancel();
                        Helper.gotoLogin(isSuccess);//token失效去重新登陆
                        QuestionBean qdata = (QuestionBean) o;

                        EventBus.getDefault().postSticky(qdata);
                        if (Constant.adutst.equals(id[1])){//行测
                            //行测
                            intent = new Intent(getActivity(), QuestionTestActivity.class);
                            intent.putExtra(QuestionTestActivity.IS_EXAM, true);

                        }
                        if (Constant.essay.equals(id[1])){//申论
                            //申论
                            intent = new Intent(getActivity(), ExpositionTestActivity.class);

                        }
                        startActivity(intent);

                    }

                    @Override
                    public void onFailure(String fail) {
                        Helper.showToast("获取题库失败");
                        dialog.cancel();
                    }
                });
                break;
            case 3:// 页面（须知）
                intent = new Intent(getContext(), NeedNoticeDetailActivity.class);
                intent.putExtra("type", bannerList.get(position).getLinkurl());
                startActivity(intent);
                break;

        }
    }


    @Override
    protected void initData() {


    }

    @Override
    protected void addOnClick() {

    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle
            savedInstanceState) {
        // TODO: inflate a fragment view
        View rootView = super.onCreateView(inflater, container, savedInstanceState);
        unbinder = ButterKnife.bind(this, rootView);
        return rootView;
    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
        unbinder.unbind();
    }


}
